import java.util.HashMap;
import java.util.Map;

public class A01TowSum {
    public static void main(String[] args) {
        int[] nums = {2, 25, 11, 7};
        int target = 9;

//        int[] answer = twoSum(nums, target);
        int[] answer = optimizeTwoSum(nums, target);
        //打印答案
        if (answer.length != 0) System.out.println("[" + answer[0] + "," + answer[1] + "]");
        else System.out.println("不存在满足情况的数！");
    }

    //暴力枚举法
    public static int[] twoSum(int[] nums, int target) {
        int len = nums.length;  //数组长度
        for (int i = 0; i < len - 1; i++) { // i —— len-1
            for (int j = i + 1; j < len; j++) { // i+1 —— len
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }

    //查表法(哈希表)
    public static int[] optimizeTwoSum(int[] nums, int target) {
        //因为对数据的顺序没有要求，所以使用hashMap(差值为键，索引下标为值)
        Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            //判断hashMap中是否包含键
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }
}

